#!/bin/bash
#coding.net docker部署流程
imageName='sprite-space-docker.pkg.coding.net/xxxx/xxxx/xxxx'
imageVersion='${trigger["artifacts"].?[name=="'$imageName'"][0]["version"]}'
docker login -u ${username} -p ${password} sprite-space-docker.pkg.coding.net
docker pull $imageName:$imageVersion

# 容器名称
containerBaseName="nest-api"
# 容器端口列表
ports=(10001 10002 10003)
# 应用内端口号
appPort=3000
# Nginx配置文件路径
nginxConf='/www/server/panel/vhost/nginx/www.spritedance.com.conf'

# # 重启容器的函数
restart_container() {
    local container_name=$1
    local port=$2
    local version=$3

    # 停止并删除旧容器
	echo "部署$port：删除旧容器"
    docker stop "$container_name" || true
    docker rm -f "$container_name" || true
	sleep 3
    # 启动新容器
	echo "部署$port：启动新容器"
    docker run -d --name "$container_name" -p "$port:$appPort" \
        --restart=always \
        $imageName:"$version"
}

# 滚动更新
for port in ${ports[@]}
do
    # 标记旧服务器为down
    sed -i "s/server 127.0.0.1:$port;/server 127.0.0.1:$port down;/" $nginxConf
	echo "部署$port：修改nginx配置"
    nginx -s reload

    # 等待一段时间，确保旧请求完成
    sleep 20

    # 启动新容器
    container_name="$containerBaseName-$port"
    version=$imageVersion
    restart_container "$container_name" "$port" "$version"

	# 等待新容器启动完成
  	sleep 10

    # 恢复服务器
	sed -i "s/server 127.0.0.1:$port down;/server 127.0.0.1:$port;/" $nginxConf
	echo "部署$port:恢复nginx配置"
    nginx -s reload
done

# 清除旧镜像
# 检查是否存在符合条件的旧镜像
echo "清除旧镜像"
old_images=$(docker images --format "{{.Repository}}:{{.Tag}}" | grep $containerBaseName | grep -v -f - < <(docker ps --format '{{.Image}}'))

if [ -n "$old_images" ]; then
    # 存在旧镜像，运行删除命令
    echo "Deleting old images:"
    echo "$old_images" | xargs docker rmi
else
    echo "No old images found."
fi
